package dao.Item;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import model.Item;
import abstractFactory.Factory;

public class ItemDAOJPA implements ItemDAO{
	static EntityManager manager;

	public EntityManager getManager() {
		if(manager == null) {
			manager = Factory.getFactory().createEntityManager();
		}
		return manager;
	}

	public boolean save(Item item) {
		try	{
			getManager().getTransaction().begin();		
			getManager().persist(item);
			getManager().getTransaction().commit();
			return true;
		}catch (Exception e) {
			return false;
		}
	}

	public boolean update(Item item){
		try{
			getManager().getTransaction().begin();
			getManager().merge(item);
			getManager().getTransaction().commit();
			return true;
		}catch (Exception e) {
			return false;
		}
	}

	public boolean delete(Item item){
		try {
			Item i = getManager().find(Item.class,item.getId());
			getManager().getTransaction().begin();
			getManager().remove(i);
			getManager().getTransaction().commit();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public List<Item> getAllItems(){
		Query query = (Query) getManager().createQuery("SELECT i FROM Item i" );
		@SuppressWarnings("unchecked")
		List<Item> items = (List<Item>)query.getResultList();
		return items;
	}

	public Long getTotalItems(){
		Query query = (Query) getManager().createQuery("SELECT count(i) FROM Item i" );
		Long total = (Long) query.getSingleResult();
		return total;
	}

	public Item getItemById(int id)	{
		try {
			Item item = getManager().find(Item.class, id);
			return item;
		} catch (Exception e) {
			return null;				
		}
	}
}
